//引入pixi引擎 
import * as PIXI from "@tbminiapp/pixi-miniprogram-engine";
import { TweenMax, TimelineMax, Power0 } from './libs/tween/index.js';
const width = 726;
const height = 726;
// 纹理集合
const myTextureCollect = {};
Component({
  // 供pixi渲染的canvas
  pixiCanvas: null,
  application: null,
  data: {
    current_page_name: '动画页',
    custom_page_into_time: '',
    targetWidth: 726,
    targetHeight: 726,
    isRunCanvas: false,
  },
  props: {
    onSwitchPage: (n) => {},
  },
  didMount() {
    this.setData({
      isRunCanvas: true,
    })
  },
  didUnmount() {
  },
  methods: {
    onCanvasReady() {
      // my.mfutil.logger.set({ origin: 'canvas.js', msg: 'onCanvasReady' });
      const { registerCanvas, devicePixelRatio } = PIXI.miniprogram
      // 建立canvas引用
      try {
        my.createCanvas({
          id: "iCanvas",
          success: async (canvas) => {
            const systemInfo = $global.mfutil.mobileInfo || my.getSystemInfoSync()
            // 拿到当前设备的宽高
            const dpr = systemInfo.pixelRatio
            let { windowWidth, platform } = systemInfo;
            // 折算 resolution
            const resolution = windowWidth / (width / 2) * (dpr / 2);
            this.canvas = canvas;
            this.pixiCanvas = canvas;
            registerCanvas(canvas);
            // 为pixi引擎注册当前的canvas
            let context = canvas.getContext('2d');
            this.context = context;
            this.application = new PIXI.Application({           // canvas.getContext('webgl') 
              width,
              height,
              view: canvas,
              context: context,
              transparent: true,
              forceCanvas: true,                  // 强制使用2d上下文进行渲染，如果为flase, 则默认使用webgl渲染 
              resolution,                         // 设置resolution 为像素密度 
            })
            // 业务处理
            this.pixiInit();
          },
          fail: e => {
            $global.mfutil.logger.log(e, 'canvas.js-fail');
          }
        });
      } catch (e) {
        $global.mfutil.logger.log(e, 'canvas.js-catchs');
      }

    },
    async pixiInit() {
      // 画一个矩形
      let graphics = new PIXI.Graphics();
      graphics.beginFill(0x66CCFF);
      // 边框颜色
      graphics.lineStyle(4, 0x66CCFF, 1);
      //调用drawRect方法来画一个矩形，四个参数是x, y, width 和 height，其中x和y确定矩形的位置
      graphics.drawRect(50, 50, 100, 100);
      // 结束绘制
      graphics.endFill();
      this.application.stage.addChild(graphics);
      $global.mfutil.logger.log('方块写完了', 'canvas.js');

      // 画一个图案
      let texture = await this.loaderTexture('https://morefun-active.oss-cn-beijing.aliyuncs.com/morefun2022/test/logo_01.png');
      let imgB = new PIXI.Sprite(texture);
      imgB.x = 375;
      imgB.y = 375;
      this.application.stage.addChild(imgB);

    },
    // 根据图片名称获取纹理
    async getTexureByName(textures, name) {
      const obj = liveCardJson.frames[name];
      if (!obj) return;
      const texture = new PIXI.Texture(
        textures,
        new PIXI.Rectangle(obj.frame.x, obj.frame.y, obj.rotated ? obj.frame.h : obj.frame.w, obj.rotated ? obj.frame.w : obj.frame.h),
        new PIXI.Rectangle(0, 0, obj.sourceSize.w, obj.sourceSize.h),
        new PIXI.Rectangle(obj.spriteSourceSize.x, obj.spriteSourceSize.y, obj.spriteSourceSize.w, obj.spriteSourceSize.h),
        obj.rotated ? 2 : 0
      );
      return texture;
    },
    // 加载
    async loaderTexture(url, name) {
      return new Promise((resolve, reject) => {
        try {
          if (name && myTextureCollect && myTextureCollect['texture_' + name]) {
            resolve(myTextureCollect['texture_' + name]);
          }
          const alias = `texture_${new Date().getTime()}_${Math.floor(Math.random() * 1000000 + 1)}`;
          // V6 版本加载
          // const loader = new PIXI.Loader();
          // V4 版本加载
          const loader = new PIXI.loaders.Loader();
          loader.add(alias, url);
          loader.load((loader, resources) => {
            const textureCollect = resources[alias].texture;
            if (name) {
              myTextureCollect['texture_' + name] = textureCollect;
            }
            resolve(textureCollect);
          })
        } catch (e) {
          throw new Error('获取纹理,出现异常');
        }
      });
    },
    // 通过 Id 获取小块组件的纹理
    async getOrLoaderTextureById(id) {
      if (id && myTextureCollect && myTextureCollect['texture_' + id]) {
        return (myTextureCollect['texture_' + id]);
      }
      // baseUrl
      const url = `${this.data.baseUrl}/${id}.png?x-oss-process=image/resize,m_fixed,h_600,w_600`;
      return await this.loaderTexture(url, id)
    },
    // 加载纹理并缓存起来 根据 url 和 name 获取一个纹理
    async loaderTexture(url, name) {
      return new Promise((resolve, reject) => {
        try {
          if (name && myTextureCollect && myTextureCollect['texture_' + name]) {
            resolve(myTextureCollect['texture_' + name]);
          }
          const alias = `texture_${new Date().getTime()}_${Math.floor(Math.random() * 1000000 + 1)}`;
          // V6 版本加载
          // const loader = new PIXI.Loader();
          // V4 版本加载
          const loader = new PIXI.loaders.Loader();
          loader.add(alias, url);
          loader.load((loader, resources) => {
            const textureCollect = resources[alias].texture;
            if (name) {
              myTextureCollect['texture_' + name] = textureCollect;
            }
            resolve(textureCollect);
          })
        } catch (e) {
          throw new Error('获取纹理,出现异常');
        }
      });
    },
    // 监听小程序canvas的touch事件，并触发pixi内部事件
    onTouchHandle(event) {
      if (this.pixiCanvas && event.changedTouches && event.changedTouches.length) {
        this.pixiCanvas.dispatchEvent(event);
      }
    },
  },
});

